package app.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFormattedTextField;
import javax.swing.JTextField;
import app.calculator.Fomular;
import app.ui.MainFrame;

public class AppAction implements ActionListener, FocusListener {
	MainFrame mainFrame = null;
	boolean multiple1000 = true;
	JFormattedTextField[] jFields = null;

	public AppAction(MainFrame mainFrame) {
		this.mainFrame = mainFrame;
		jFields = mainFrame.getjTextFields();
	}

	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();

		if (obj instanceof JTextField) {
			jTextFieldAction(obj);
		} else if (obj instanceof JButton) {
			jButtonAction(obj);
		} else if (obj instanceof JCheckBox) {
			jCheckBoxAction(obj);
		}
	}

	private void jCheckBoxAction(Object obj) {
		JCheckBox jCheckBox = (JCheckBox) obj;
		multiple1000 = jCheckBox.isSelected();
	}

	private void jButtonAction(Object obj) {
		Fomular fomular = new Fomular();
		JButton jButton = (JButton) obj;
		int type = 1;
		
		if(jButton.getText().equals("Calculate 2.")) {
			type = 2;
		}

		float[] str = new float[4];
		
		doResetValue();
		for (int i = 0; i < 4; i++) {
			str[i] = (Float) jFields[i].getValue();
		}

		String[] out = fomular.export(str[0], str[1], str[2], (int) str[3],
				type);
		int num = out.length;
		
		if(num == jFields.length) {
			for (int i = 0; i < num; i++) {
				jFields[i].setValue(Float.valueOf(out[i]));
			}
		}
	}

	private void jTextFieldAction(Object obj) {
		JTextField jTextField = (JTextField) obj;

		String str = jTextField.getText();
		System.out.println(str);
	}

	public boolean isMultiple1000() {
		return multiple1000;
	}

	public void focusGained(FocusEvent e) {
		Object obj = e.getSource();
		if(obj instanceof JFormattedTextField) {
			JFormattedTextField jField = (JFormattedTextField) obj;			
			jField.setText(null);
			
			if(!jField.equals(jFields[0])) {
				doResetValue();
			}
		}
	}
	
	
	public void focusLost(FocusEvent e) {
	}

	private void doResetValue() {
		if(multiple1000) {
			JFormattedTextField jField = jFields[0];
			float f = (Float) jField.getValue();
			
			if(f < 999999) {
				f *= 1000;
				jField.setValue(Float.valueOf(f));
			}
		}
	}

}
